import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/integral_detail.dart';
import 'package:kxy_flutter_app/r.dart';
import 'package:kxy_flutter_app/view/my/integral/integral_rules_view.dart';
import 'package:kxy_flutter_app/view/my/integral/integral_view.dart';

class IntegralTodayView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return IntegralTodayViewState();
  }
}

class IntegralTodayViewState extends State<IntegralTodayView> {
  Future loadFuture;
  IntegralDetail integral;
  DateTime date = DateTime.now();

  @override
  void initState() {
    loadFuture = loadIntegral();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return backgroundWidget(Scaffold(
      backgroundColor: Colors.transparent,
      appBar: AppBar(
        title: Text('积分中心', style: TextStyle(color: Colors.white)),
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
        centerTitle: true,
        backgroundColor: Colors.transparent,
        actions: [gotoRankAction(), gotoRulesAction()],
      ),
      body: FutureBuilder(
        future: loadFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return integralBody();
          }
          return LoadingWidget();
        },
      ),
    ));
  }

  Widget integralBody() {
    var format = new DateFormat('yyyy-MM-dd HH:mm:ss');
    var integralList = Column(
      children: ListTile.divideTiles(
        context: context,
        color: Colors.black12,
        tiles: integral.items.map((item) {
          return ListTile(
            dense: true,
            title: Text(item.ruleName),
            subtitle: Text(format.format(item.createTime)),
            trailing: Text(item.grade.toString() + '分'),
          );
        }).toList()
          ..insert(0, todayIntegralInfo()),
      ).toList(),
    );

    return Column(
      children: [
        totalIntegral(),
        Expanded(
          child: SingleChildScrollView(
            padding: EdgeInsets.symmetric(vertical: 10),
            child: Container(
              color: Colors.white,
              child: integralList,
            ),
          ),
        ),
      ],
    );
  }

  Widget gotoRulesAction() {
    return FlatButton(
      textColor: Colors.white,
      child: Text('规则'),
      onPressed: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (cxt) => IntegralRulesView(),
          ),
        );
      },
    );
  }

  Widget gotoRankAction() {
    return FlatButton(
      textColor: Colors.white,
      child: Text('排行'),
      onPressed: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (cxt) => IntegralView(),
          ),
        );
      },
    );
  }

  Widget totalIntegral() {
    return Container(
      height: 120,
      color: Colors.transparent,
      child: Column(
        children: [
          Text(
            '总积分',
            style: TextStyle(color: Colors.white),
          ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 10),
            child: Text(
              integral.totalGrade.toString(),
              style: TextStyle(fontSize: 40, color: Colors.white),
            ),
          ),
          Text(
            '${integral.deptName} - ${integral.realName}',
            style: TextStyle(color: Colors.white),
          ),
        ],
      ),
    );
  }

  Widget todayIntegralInfo() {
    var format = new DateFormat('yyyy-MM-dd');
    return ListTile(
      title: Text('日累计 ${integral.todayTotalGrade} 分'),
      trailing: Text(
        format.format(date),
        style: TextStyle(
          color: Theme.of(context).primaryColor,
        ),
      ),
      onTap: () async {
        var selectDate = await showDatePicker(
          context: context,
          initialDate: this.date,
          firstDate: DateTime.parse('2017-01-01'),
          lastDate: DateTime.now(),
        );
        if (selectDate != null) {
          this.date = selectDate;
          loadIntegral();
        }
      },
    );
  }

  Widget backgroundWidget(Widget child) {
    var img = DecorationImage(
      image: AssetImage(R.assetsCommonBg),
      fit: BoxFit.fill,
      alignment: Alignment.topCenter,
    );

    var shadow = BoxShadow(
      color: Color.fromRGBO(0, 0, 0, 0.5),
      blurRadius: 5,
      offset: Offset(0, 1),
    );

    return Container(
      decoration: BoxDecoration(color: Colors.white),
      child: Stack(
        children: [
          Container(
            height: 120 + kToolbarHeight + MediaQuery.of(context).padding.top,
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [shadow],
              image: img,
            ),
          ),
          child,
        ],
      ),
    );
  }

  Future loadIntegral() async {
    var format = new DateFormat('yyyy-MM-dd');
    var res = await Http.instance.post(
      '/integral-app/integral/userGrade/getUserGrade',
      params: {
        'userId': Auth.instance.userId,
        'stime': format.format(date),
      },
    );
    if (res.code == 200) {
      setState(() {
        integral = IntegralDetail.fromJson(res.data);
      });
    }
  }
}
